using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Collections;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DaoService.Model;
using DaoService.Services;
using NewUI.AutoMapper;
using NewUI.Component;
using NewUI.Enum;
using NewUI.Models;
using PLCComponent;
using S7.Net;

namespace NewUI.ViewModels;

public partial class PlcListViewModel : ViewModelBase
{
    private PlcListViewModelService _modelService = new();
    public AvaloniaList<string> SimpleContent { get; } = [];
    public AvaloniaList<int> IntervalContent { get; } = [];
    public ObservableCollection<PlcList> PlcItems { get; } = new ObservableCollection<PlcList>();
    public AvaloniaList<int> TimeoutContent { get; } = [];
    
    [ObservableProperty] private PlcList _currentPlcList = new();
    
    [ObservableProperty] private bool _showEmptyImage = true;

    public PlcListViewModel()
    {
        LoadPlcList();
        SimpleContent = new()
        {
            nameof(PlcType.S71500),
            nameof(PlcType.S71200),
        };
        TimeoutContent = new()
        {
            (int)TimeOutOption.TimeOutOption_2000,
            (int)TimeOutOption.TimeOutOption_5000,
            (int)TimeOutOption.TimeOutOption_10000,
        };
        IntervalContent = new()
        {
            (int)ScanInterval.Interval500,
            (int)ScanInterval.Interval1000,
            (int)ScanInterval.Interval2000,
        };
    }

    private async Task LoadPlcList()
    {
       var list = await _modelService.GetPlcList();
       PlcItems.Clear();
       if (list.Count > 0)
       {
           ShowEmptyImage = false;
       }
       foreach (var item in list)
       {
           var plcList = PlcListMapper.ToModelMapper.Map<PlcList>(item);
           plcList.IsConnected = false;
           plcList.IsConnectLoading = false;
           plcList.plcListViewModel = this;
           plcList.Status = "已断开";
           plcList.TextColor = "Success";
           PlcItems.Add(plcList);
       }
    }
    
    [RelayCommand]
    public async Task PlcItemSelected(PlcList plcList)
    {
        _currentPlcList = plcList;
    }

    [RelayCommand]
    public async Task SavePlcList()
    { 
        var result = await _modelService.Save(_currentPlcList);
        if (result)
        {
            await LoadPlcList();
        }
    }

    [RelayCommand]
    public async Task ResetCurrentPlcList()
    {
        CurrentPlcList = new PlcList();
        ToastManager.ShowSuccessToast("重置数据成功!");
    }

    [RelayCommand]
    public async Task RemoveItem(PlcList plcList)
    {
        try
        {
            int id = Convert.ToInt32(plcList.Id);
            var result = await _modelService.Remove(id);
            if (result)
            {
                CurrentPlcList = new PlcList();
                await LoadPlcList();
                ToastManager.ShowSuccessToast("删除数据成功!");
            }
        }
        catch (Exception e)
        {
            ToastManager.ShowErrorToast("删除数据出错!" + e.Message);
        }
    }

    [RelayCommand]
    public async Task TestConnectPlcList(PlcList plcList)
    {
        var result = await _modelService.Connect(plcList);
        if (result)
        {
            ToastManager.ShowSuccessToast($"连接{plcList.Name}成功!");
        }
        else
        {
            ToastManager.ShowErrorToast($"连接{plcList.Name}失败!");
        }
    }
}
class PlcListViewModelService
{
    private PlcInfoService GetPlcInfoService()
    {
        return ServiceProvider.PlcInfoService;;
    }
    
    public async Task<bool> Save(PlcList? plcList)
    {
        //插入或更新
        try
        {
            PlcInfoEntity entity = PlcListMapper.ToEntityMapper.Map<PlcInfoEntity>(plcList);
            if (plcList == null || plcList.Id == null)
            {
                var result = await GetPlcInfoService().InsertAsync(entity);
                plcList.Id = result.ToString();
            }
            else
            {
               await GetPlcInfoService().SaveAsync(entity);
            }
            ToastManager.ShowSuccessToast("保存数据成功!");
        }
        catch (Exception e)
        {
            ToastManager.ShowErrorToast("保存数据出错" + e.Message);
            return false;
        }
        return true;
    }

    public async Task<List<PlcInfoEntity>> GetPlcList()
    {
        try
        {
            var result = await GetPlcInfoService().GetAllAsync();
            return result.ToList();
        }
        catch (Exception e)
        {
            ToastManager.ShowErrorToast("获取数据出错" + e.Message);
            return new List<PlcInfoEntity>();
        }
    }

    public async Task<bool> Remove(int id)
    {
        return await GetPlcInfoService().DeleteAsync(id);
    }

    public async Task<bool> Connect(PlcList plcList)
    {
        try
        {
            Plc plc = PlcConnectionUtil.CreateConnection(plcList.CpuType, plcList.IpAddress, (short)plcList.Rack, (short)plcList.Slot);
            await PlcConnectionUtil.OpenConnection(plc, plcList.Timeout);
            if (plc.IsConnected)
            {
                return true;
            }
            return false;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    
    
}